package org.ellisande.grid.tags;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.ellisande.grid.tags.support.TagBuilder;
import org.ellisande.tld.annotations.Attribute;
import org.ellisande.tld.annotations.Description;
import org.ellisande.tld.annotations.Tag;

@Tag
public abstract class AbstractTag extends TagSupport {

	private static final long serialVersionUID = -483787584158009829L;

	@Attribute
	@Description("CSS styles to append to the element when it is rendered.")
	protected String styles = "";

	@Attribute
	@Description("Html ID")
	protected String id = "";

	@Override
	public int doStartTag() throws JspException {
		try {
			startTag();
		} catch (Exception e) {
			throw new JspException(e);
		}
		return EVAL_BODY_INCLUDE;
	}

	@Override
	public int doEndTag() throws JspException {
		try {
			endTag();
		} catch (Exception e) {
			throw new JspException(e);
		}
		return EVAL_PAGE;
	}

	public void setStyles(String styles) {
		this.styles = styles;
	}

	@Override
	public void release() {
		super.release();
		styles = null;
		id = null;
	}

	public final TagBuilder createTagBuilder(String tagName) {
		TagBuilder tag = new TagBuilder(tagName);
		if (!styles.isEmpty()) {
			tag.addStyles(styles);
		}
		if (!id.isEmpty()) {
			tag.addAttribute("id", id);
		}
		

		return tag;
	}

	@Override
	public void setId(String newId) {
		this.id = newId;
	}

	public abstract void startTag() throws Exception;

	public abstract void endTag() throws Exception;

}
